package com.example.chcrm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.chcrm.entity.common.*;
import com.example.chcrm.entity.employee.EmployeeVo;
import com.example.chcrm.entity.employee.RoleModels;
import com.example.chcrm.entity.employee.SupplierPort;
import com.example.chcrm.mapper.LineConfigMapper;
import com.example.chcrm.mapper.OperateRecordMapper;
import com.example.chcrm.mapper.SupplierPortMapper;
import com.example.chcrm.mapper.TAreaMapper;
import com.example.chcrm.service.LineConfigService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author 邹
 * @Date 2025/4/23 13:24
 * @Version 1.0
 */
@Service
public class LineConfigServiceImpl <T> implements LineConfigService<T> {
    @Autowired
    LineConfigMapper lineConfigMapper;
    @Autowired
    TAreaMapper tAreaMapper;
    @Autowired
    private OperateRecordMapper operateRecordMapper;
    @Autowired
    private SupplierPortMapper supplierPortMapper;
    @Override
    @Transactional
    public ResponseMsg<Object> add(LineConfig lcf , EmployeeVo empVo) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        //-------------验证线路是否存在-------------
        int lineConfigCount = lineConfigMapper.selectCount(new QueryWrapper<LineConfig>()
                .eq("line_name", lcf.getLineName())
                .eq("is_deleted", 0)).intValue();
        if (lineConfigCount > 0) {
            msg.fail("操作失败，线路名称已存在");
            return msg;
        }
        int count = 0;
        if (lcf.getLineType() == BasicDoc.LINE_TYPE_1) {    //公路运输
            QueryWrapper<LineConfig> queryWrapper = new QueryWrapper<LineConfig>();
//            queryWrapper.eq("start_address_id", lcf.getStartAddressId());
//            queryWrapper.eq("end_address_id", lcf.getEndAddressId());
            queryWrapper.eq("line_type", BasicDoc.LINE_TYPE_1);
            queryWrapper.eq("is_deleted", BasicDoc.NOT_DELETE);
            if (StringUtils.isNotBlank(lcf.getDeparturePortId())) {
                queryWrapper.eq("departure_port_id", lcf.getDeparturePortId());
            } else {
                queryWrapper.isNull("departure_port_id");
                lcf.setDeparturePortId(null);
            }
            if (StringUtils.isNotBlank(lcf.getArrivePort())) {
                queryWrapper.eq("arrive_port", lcf.getArrivePort());
            } else {
                queryWrapper.isNull("arrive_port");
                lcf.setArrivePortId(null);
            }
            count = lineConfigMapper.selectCount(queryWrapper).intValue();
        } else if (lcf.getLineType() == BasicDoc.LINE_TYPE_2) {  //水路运输
            count = lineConfigMapper.selectCount(new QueryWrapper<LineConfig>()
                    .eq("departure_port", lcf.getDeparturePort())
                    .eq("arrive_port", lcf.getArrivePort())
                    .eq("line_type", BasicDoc.LINE_TYPE_2)
                    .eq("is_deleted", BasicDoc.NOT_DELETE)).intValue();
        } else {
            msg.fail("操作失败，线路类型异常");
            return msg;
        }
        if (count > 0) {
            msg.fail("操作失败，线路已存在");
            return msg;
        }
        //--------------验证起始地--------------
        if (StringUtils.isNotBlank(lcf.getDeparturePort())) {
            SupplierPort supplierPortOther = supplierPortMapper.selectOne(new QueryWrapper<SupplierPort>()
                    .eq("port_name",lcf.getDeparturePort()));
            if (supplierPortOther == null) {
                msg.fail("操作失败，起始港不存在");
                return msg;
            }
            lcf.setDeparturePortId(supplierPortOther.getId());
            lcf.setStartAddressId(supplierPortOther.getAreaId());
            lcf.setStartFullAddressId(supplierPortOther.getAreaFullId());
            lcf.setStartAddressName(supplierPortOther.getArea());
            lcf.setStartingCoordinate(supplierPortOther.getCoordinate());
            lcf.setDeparturePort(supplierPortOther.getPortName());
        } else {
            TArea tArea = tAreaMapper.selectOne(new QueryWrapper<TArea>()
                    .eq("name",lcf.getStartAddressName()));
            if (tArea == null || !tArea.getLevel().equals("district")) {
                msg.fail("操作失败，起始地不存在");
                return msg;
            }
            lcf.setStartAddressId(tArea.getAdCode());
            lcf.setStartFullAddressId(tArea.getParentCodeLis());
            lcf.setStartAddressName(tArea.getParentNameLis());
            lcf.setStartingCoordinate(tArea.getCenter());
            lcf.setDeparturePort(null);
        }
        //--------------验证目的地--------------
        if (StringUtils.isNotBlank(lcf.getArrivePort())) {
            SupplierPort supplierPortOther = supplierPortMapper.selectOne(new QueryWrapper<SupplierPort>()
                    .eq("port_name",lcf.getArrivePort()));
            if (supplierPortOther == null) {
                msg.fail("操作失败，目的港不存在");
                return msg;
            }
            lcf.setArrivePortId(supplierPortOther.getId());
            lcf.setEndAddressId(supplierPortOther.getAreaId());
            lcf.setEndFullAddressId(supplierPortOther.getAreaFullId());
            lcf.setEndAddressName(supplierPortOther.getArea());
            lcf.setDeliveryCoordinate(supplierPortOther.getCoordinate());
            lcf.setArrivePort(supplierPortOther.getPortName());
        } else {
            TArea tArea = tAreaMapper.selectOne(new QueryWrapper<TArea>()
                    .eq("name",lcf.getEndAddressName()));
            if (tArea == null || !tArea.getLevel().equals("district")) {
                msg.fail("操作失败，目的地不存在");
                return msg;
            }
            lcf.setEndAddressId(tArea.getAdCode());
            lcf.setEndAddressId(tArea.getAdCode());
            lcf.setEndFullAddressId(tArea.getParentCodeLis());
            lcf.setEndAddressName(tArea.getParentNameLis());
            lcf.setDeliveryCoordinate(tArea.getCenter());
            lcf.setArrivePort(null);
        }
        String uuid = RandomHelper.uuid();
        lcf.setId(uuid);
        lcf.setStatus(1);
        lcf.setIsDeleted(BasicDoc.NOT_DELETE);
        lineConfigMapper.insert(lcf);
        //添加操作日志

        OperateRecord ope = new OperateRecord();
        ope.setId(RandomHelper.uuid());
        ope.setOperateType(OperateRecord.OPE_ADD);
        ope.setSourceId(uuid);
        if (empVo != null) {
            ope.setOperationId(empVo.getId());
            ope.setOperationName(empVo.getEmpNm());
        }
        operateRecordMapper.insert(ope);
        msg.success("操作成功");
        return msg;
    }

    @Override
    @Transactional
    public ResponseMsg<Object> disable(LineConfig roleModels,EmployeeVo empVo) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        String id = roleModels.getId();
        LineConfig lineConfig = lineConfigMapper.selectById(id);
        if (lineConfig == null || lineConfig.getIsDeleted() != BasicDoc.NOT_DELETE) {
            msg.fail("添加失败，数据未找到");
            return msg;
        }
        lineConfig.setStatus(lineConfig.getStatus() == BasicDoc.IS_USE ? BasicDoc.STOP_USE : BasicDoc.IS_USE);

        lineConfigMapper.updateById(lineConfig);
        //添加操作日志
        OperateRecord ope = new OperateRecord();
        ope.setId(RandomHelper.uuid());
        ope.setOperateType(lineConfig.getStatus() == BasicDoc.IS_USE ? OperateRecord.OPE_CLOSE : OperateRecord.OPE_OPEN);
        ope.setSourceId(id);
        if (empVo != null) {
            ope.setOperationId(empVo.getId());
            ope.setOperationName(empVo.getEmpNm());
        }
        operateRecordMapper.insert(ope);
        msg.success("操作成功");
        return msg;
    }

    @Override
    public ResponseMsg<IPage<LineConfig>> pageList(LineConfig lcf) {
        QueryWrapper<LineConfig> query = new QueryWrapper<>();
        //模糊查询
        if (StringUtils.isNotBlank(lcf.getLineName())) {
            query.like("line_name", lcf.getLineName());
        }
        if (lcf.getLineType() != null) {
            query.eq("line_type", lcf.getLineType());
        }
        if (StringUtils.isNotBlank(lcf.getStartAddressName())) {
            query.like("start_address_name", lcf.getStartAddressName());
        }
        if (StringUtils.isNotBlank(lcf.getEndAddressName())) {
            query.like("end_address_name", lcf.getEndAddressName());
        }
        if (StringUtils.isNotBlank(lcf.getDeparturePort())) {
            query.like("departure_port", lcf.getDeparturePort());
        }
        if (StringUtils.isNotBlank(lcf.getArrivePort())) {
            query.like("arrive_port", lcf.getArrivePort());
        }
        if (lcf.getStatus() != null) {
            query.eq("status", lcf.getStatus());
        }
        query.orderByDesc("create_time");//按时间倒序排序
        List<LineConfig> list = lineConfigMapper.selectList(query);
        ResponseMsg<IPage<LineConfig>> iPageResponseMsg = new ResponseMsg<>();
        Page<LineConfig> page = new Page<>();
        page.setRecords(list);
        page.setTotal(list.size());
        page.setSize(lcf.getRows());
        page.setCurrent(lcf.getPage());
        iPageResponseMsg.setData(page);
        iPageResponseMsg.success("查询成功");
        return iPageResponseMsg;
    }

    @Override
    @Transactional
    public ResponseMsg<Object> update(LineConfig lcf,EmployeeVo empVo) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        LineConfig lineConfig = lineConfigMapper.selectById(lcf.getId());
        if (lineConfig == null || lineConfig.getIsDeleted() != BasicDoc.NOT_DELETE) {
            msg.fail("操作失败，数据不存在");
            return msg;
        }
        //-----------验证线路名是否存在-----------
        int lineConfigCount = lineConfigMapper.selectCount(new QueryWrapper<LineConfig>()
                .eq("line_name", lcf.getLineName())
                .ne("id", lcf.getId())
                .eq("is_deleted", BasicDoc.NOT_DELETE)).intValue();
        if (lineConfigCount > 0) {
            msg.fail("操作失败，线路名称已存在");
            return msg;
        }
        //-----------验证线路是否存在-----------
        int count = 0;
        if (lcf.getLineType() == BasicDoc.LINE_TYPE_1) {
            QueryWrapper<LineConfig> query = new QueryWrapper<LineConfig>();
            query.eq("start_address_id", lcf.getStartAddressId());
            query.eq("end_address_id", lcf.getEndAddressId());
            query.eq("line_type", BasicDoc.LINE_TYPE_1);
            query.eq("is_deleted", BasicDoc.NOT_DELETE);
            query.ne("id", lineConfig.getId());
            if (StringUtils.isNotBlank(lcf.getDeparturePortId())) {
                query.eq("departure_port_id", lcf.getDeparturePortId());
            } else {
                query.isNull("departure_port_id");
                lcf.setDeparturePortId(null);
            }
            if (StringUtils.isNotBlank(lcf.getArrivePortId())) {
                query.eq("arrive_port_id", lcf.getArrivePortId());
            } else {
                query.isNull("arrive_port_id");
                lcf.setArrivePortId(null);
            }
            count = lineConfigMapper.selectCount(query).intValue();
        } else if (lcf.getLineType() == BasicDoc.LINE_TYPE_2) {
            count = lineConfigMapper.selectCount(new QueryWrapper<LineConfig>()
                    .eq("departure_port_id", lcf.getDeparturePortId())
                    .eq("arrive_port_id", lcf.getArrivePortId())
                    .eq("line_type", BasicDoc.LINE_TYPE_2)
                    .eq("is_deleted", BasicDoc.NOT_DELETE)
                    .ne("id", lineConfig.getId())).intValue();
        } else {
            msg.fail("操作失败，线路类型异常");
            return msg;
        }
        if (count > 0) {
            msg.fail("操作失败，线路已存在");
            return msg;
        }
        //--------------验证起始地--------------
        if (StringUtils.isNotBlank(lcf.getDeparturePortId())) {
            if (lineConfig.getDeparturePortId() == null || !lcf.getDeparturePortId().equals(lineConfig.getDeparturePortId())) {
                SupplierPort supplierPortOther = supplierPortMapper.selectById(lcf.getDeparturePortId());
                if (supplierPortOther == null) {
                    msg.fail("操作失败，起始港不存在");
                    return msg;
                }
                lineConfig.setStartAddressId(supplierPortOther.getAreaId());
                lineConfig.setStartFullAddressId(supplierPortOther.getAreaFullId());
                lineConfig.setStartAddressName(supplierPortOther.getArea());
                lineConfig.setStartingCoordinate(supplierPortOther.getCoordinate());
                lineConfig.setDeparturePortId(supplierPortOther.getId());
                lineConfig.setDeparturePort(supplierPortOther.getPortName());
            }
        } else {
            if (!lcf.getStartAddressId().equals(lineConfig.getStartAddressId())) {
                TArea tArea = tAreaMapper.selectById(lcf.getStartAddressId());
                if (tArea == null || !tArea.getLevel().equals("district")) {
                    msg.fail("操作失败，起始地不存在");
                    return msg;
                }
                lineConfig.setStartAddressId(tArea.getAdCode());
                lineConfig.setStartFullAddressId(tArea.getParentCodeLis());
                lineConfig.setStartAddressName(tArea.getParentNameLis());
                lineConfig.setStartingCoordinate(tArea.getCenter());
                lineConfig.setDeparturePort(null);
            }
        }
        //--------------验证目的地--------------
        if (StringUtils.isNotBlank(lcf.getArrivePortId())) {
            if (lineConfig.getArrivePortId() == null || !lcf.getArrivePortId().equals(lineConfig.getArrivePortId())) {
                SupplierPort supplierPortOther = supplierPortMapper.selectById(lcf.getArrivePortId());
                if (supplierPortOther == null) {
                    msg.fail("操作失败，目的港不存在");
                    return msg;
                }
                lineConfig.setEndAddressId(supplierPortOther.getAreaId());
                lineConfig.setEndFullAddressId(supplierPortOther.getAreaFullId());
                lineConfig.setEndAddressName(supplierPortOther.getArea());
                lineConfig.setDeliveryCoordinate(supplierPortOther.getCoordinate());
                lineConfig.setArrivePortId(supplierPortOther.getId());
                lineConfig.setArrivePort(supplierPortOther.getPortName());
            }
        } else {
            if (!lcf.getEndAddressId().equals(lineConfig.getEndAddressId())) {
                TArea tArea = tAreaMapper.selectById(lcf.getEndAddressId());
                if (tArea == null || !tArea.getLevel().equals("district")) {
                    msg.fail("操作失败，目的地不存在");
                    return msg;
                }
                lineConfig.setEndAddressId(tArea.getAdCode());
                lineConfig.setEndFullAddressId(tArea.getParentCodeLis());
                lineConfig.setEndAddressName(tArea.getParentNameLis());
                lineConfig.setDeliveryCoordinate(tArea.getCenter());
                lineConfig.setArrivePort(null);
            }
        }
        lineConfig.setLineName(lcf.getLineName());
        lineConfig.setLineType(lcf.getLineType());
        lineConfigMapper.updateById(lineConfig);
        //添加操作日志
        OperateRecord ope = new OperateRecord();
        ope.setId(RandomHelper.uuid());
        ope.setOperateType(OperateRecord.OPE_UPDATE);
        ope.setSourceId(lcf.getId());
        if (empVo != null) {
            ope.setOperationId(empVo.getId());
            ope.setOperationName(empVo.getEmpNm());
        }
        operateRecordMapper.insert(ope);
        msg.success("操作成功");
        return msg;
    }

    @Override
    @Transactional
    public ResponseMsg<Object> delete(String id,EmployeeVo empVo) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        LineConfig config = lineConfigMapper.selectById(id);
        if (config == null || config.getIsDeleted() != BasicDoc.NOT_DELETE) {
            msg.fail("操作失败，数据未找到");
            return msg;
        }
        //验证数据是否在使用
//        int num = transportChildCvMapper.selectCount(new QueryWrapper<TransportChildCv>()
//                .and(wrapper -> wrapper.eq("line1_id", config.getId()).or().eq("line2_id", config.getId())
//                        .or().eq("line3_id", config.getId()))
//                .eq("is_deleted", BasicDoc.NOT_DELETE));
//        if (num > 0) {
//            msg.fail("操作失败，数据使用中");
//            return msg;
//        }
        lineConfigMapper.update(null,new UpdateWrapper<LineConfig>().set("is_deleted",-1).eq("id",id));
        //添加操作日志
        OperateRecord ope = new OperateRecord();
        ope.setId(RandomHelper.uuid());
        ope.setOperateType("删除");
        ope.setSourceId(id);
        if (empVo != null) {
            ope.setOperationId(empVo.getId());
            ope.setOperationName(empVo.getEmpNm());
        }
        operateRecordMapper.insert(ope);
        msg.success("删除成功");
        return msg;
    }

    @Override
    public ResponseMsg<Object> detail(String id) {
        LineConfig lineConfig = lineConfigMapper.selectById(id);
        if (lineConfig != null) {
            //查询操作日志
            QueryWrapper<OperateRecord> opQuery = new QueryWrapper<>();
            opQuery.eq("sourceId", id).orderByDesc("create_time");
            List<OperateRecord> operateRecordList = operateRecordMapper.selectList(opQuery);
            lineConfig.setOperateRecordList(operateRecordList);
        }
        ResponseMsg<Object> msg = new ResponseMsg<>();
        msg.setData(lineConfig);
        msg.success("查询成功");
        return msg;
    }
}
